//
//  CGQshebeiInfoEditVC.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2021/4/8.
//  Copyright © 2021 叁拾叁. All rights reserved.
//


import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then
import SDCycleScrollView
import IQKeyboardManagerSwift
class CGQshebeiInfoEditVC: SYBaseTableViewController {
    
    
    var  model: CGQshebeiinfoModel!

//
    
    var  dicParams: [String : String] = [:]
    
    
    var id: String!
    
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//        IQKeyboardManager.shared.keyboardDistanceFromTextField = 60
//    }
    
    init(id: String) {
        super.init(nibName: nil, bundle: nil)
        self.id = id
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    var delete: UIButton = {
        let v = UIButton()
        v.setTitle("保存", for: .normal)
        v.setTitleColor(UIColor.white, for: .normal)
        v.titleLabel?.font = 18.autoFontSize()
        v.layer.cornerRadius = 3
        v.layer.masksToBounds = true
        v.backgroundColor = UIColor(hex: 0x0782FF)
        return v
    }()
 
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setTableView()
        setNoDataView()
        setupViewModel()
        self.title = "编辑设备信息"
        self.view.backgroundColor = Constant.bgViewColor
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
    }
    
    
    
    @objc func rightAction() {
        
    }
    
    fileprivate func setupViewModel() {
        
        requestVM.baseRequest(disposeBag: dispose, type: .sheDetail(id: self.id), modelClass: SGBaseModel<CGQshebeiinfoModel>.self) {[weak self] (res) in
            
            if let `self` = self  {
                self.model = res.data ?? CGQshebeiinfoModel()
                self.dicParams["id"] = self.model.id
                self.dicParams["deviceId"] = self.model.deviceId
                self.dicParams["protocolId"] = self.model.protocolId
                self.dicParams["deviceComment"] = self.model.deviceComment
                self.dicParams["deviceLocation"] = self.model.deviceLocation
                self.dicParams["deviceName"] = self.model.deviceName
                self.dicParams["portId"] = self.model.portId
                self.dicParams["protocolDeviceTypeId"] = self.model.protocolDeviceTypeId

                self.loadDataSuccessed()
            }
            
        } Error: {
            
        }
    }
    
    func loadDataSuccessed() {
        DispatchQueue.main.async {
            
            self.setDataSource()
        }
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT-BOTTOM_SAFE_HEIGHT-64.autoWidth()), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = .clear
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)
        
        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    
                    if indexPath.row == 1 {
                        let selectVC = CGQselectPortViewController(id: self.model.protocolDeviceTypeId ?? "", type: "port")
                        selectVC.passParamsClosure = {[weak self] value in
                            if let `self` = self {
                                let v:CGQduankouModel = value as! CGQduankouModel
                             
                                print( v.portName ?? "" )
                                
                                self.model.portName = v.portName
                                self.dicParams["portId"] = v.id

                                self.dicParams["protocolId"] = v.protocolId
                                
                                self.tableView.reloadRows(at: [indexPath], with: .none)
                                
//                                self .setupViewModel()
                            }
                        }
                        self.sy_push(selectVC)
                         
                    }
                    
                    else if indexPath.row == 3 {
                        
                        let selectVC = CGQselectPortViewController(id: self.model.protocolId ?? "",  type: "type")
                        selectVC.passParamsClosure = {[weak self] value in
                            if let `self` = self {
                                let v:CGQduankouModel = value as! CGQduankouModel
                             
                                print( v.protocolDeviceTypeName ?? "" )
                                
                                self.model.protocolDeviceTypeName = v.protocolDeviceTypeName
                                self.dicParams ["protocolDeviceTypeId"] = v.id
                                
                                self.tableView.reloadRows(at: [indexPath], with: .none)
                                
//                                self .setupViewModel()
                            }
                        }
                        self.sy_push(selectVC)
                        
                    }
                    
                }
               
            })
            .disposed(by:dispose)
        
        delete.frame = CGRect(x: 10.autoWidth(), y: SCREEN_HEIGHT - 64.autoWidth() - BOTTOM_SAFE_HEIGHT, width: SCREEN_WIDTH - 20.autoWidth(), height: 44.autoWidth())
        delete.addTarget(self, action: #selector(saveEditInfo), for: .touchUpInside)
        self.view.addSubview(delete)
    }
    
    @objc func saveEditInfo(btn:UIButton){
        
        if self.dicParams.count == 0 {
            
            return
            
        }
        
        print(self.dicParams ?? "")
        
        requestVM.baseRequest(disposeBag: dispose, type: .editDeviceDetail(dic: self.dicParams), modelClass: SGBaseModel<CGQshebeiinfoModel>.self) {[weak self] (res) in
            
            if let `self` = self  {
        
                self.popVC()
                
//                self.loadDataSuccessed()
            }
            
        } Error: {
            
        }
        
        
    }
    
    func setNoDataView() {
        
        
        
     
        
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    
    func setDataSource() {
        //初始化数据
        let sections = Observable.just([
            CGQshebeiinfoModelSection(header: "", items: [CGQshebeiinfoModel(), CGQshebeiinfoModel(),CGQshebeiinfoModel(),CGQshebeiinfoModel(),CGQshebeiinfoModel(),CGQshebeiinfoModel(),CGQshebeiinfoModel(),CGQshebeiinfoModel(),CGQshebeiinfoModel()])//self.vm.dataSource)
        ])
        
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<CGQshebeiinfoModelSection>(
           //设置单元格
            configureCell: { ds, tv, ip, item in
                
                let cell: CGQshebeiInfoEditCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                    as? CGQshebeiInfoEditCell ?? CGQshebeiInfoEditCell(style: .default, reuseIdentifier: "Cell")
                cell.configureView(model: self.model,row: ip.row)
                cell.selectionStyle = .none
                
              
                
                if ip.row == 2{
                    
                    cell.backgroundColor = UIColor(hex: 0xf0f0f0)
                    cell.bgView.backgroundColor = UIColor(hex: 0xf0f0f0)
                    
                }
                    
                if ip.row == 4 {
                    cell.passParamsClosure = {[weak self] value in
                        if let `self` = self {
                            
                            self.dicParams["deviceId"] = (value as? String)
                        }
                    }
                    
                }
                if ip.row == 5 {
                    cell.passParamsClosure = {[weak self] value in
                        if let `self` = self {
                            
                            self.dicParams["deviceName"] = value  as? String
                        }
                    }
                    
                }
                
                if ip.row == 7 {
                    cell.passParamsClosure = {[weak self] value in
                        if let `self` = self {
                            self.dicParams["deviceLocation"] = value  as? String

                        }
                    }
                    
                }
                if ip.row == 8 {
                    
                    cell.passParamsClosure = {[weak self] value in
                        if let `self` = self {
                            self.dicParams["deviceComment"] = value  as? String

                            
                        }
                    }
                    
                }
                return cell
                
            },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
            })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    
}


//自定义Section
//struct ACGQshebeiinfoModelSection {
//    var header: String
//    var items: [Item]
//}
//
//extension ACGQshebeiinfoModelSection : AnimatableSectionModelType {
//    typealias Item = CGQshebeiinfoModel
//
//    var identity: String {
//        return header
//    }
//
//    init(original: ACGQshebeiinfoModelSection, items: [Item]) {
//        self = original
//        self.items = items
//    }
//}
//
//extension CGQshebeiinfoModel: IdentifiableType {
//    var identityw: String {
//        return id!
//    }
//
//    typealias Identityw = String
//}



